<template>
  <a-modal
    title="修改租約-費用清單"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['roomId']" /></a-form-item>
              <a-row :gutter="6">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="押金"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columnsYj"
                                :dataSource="yjData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="amount" slot-scope="text, record">
                                <a-input-number
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleYjChange(e,record.key, 'amount')"
                                    :step="10"/>
                              </template>
                              <template slot="quantity" slot-scope="text, record">
                                <a-input-number
                                    v-if="record.deposittype === 1 || record.deposittype === '1'"
                                    style="width:100%"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleYjChange(e,record.key,'quantity')"
                                    :step="1"/>
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="removeYj(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                  <a-col :span="4">
                    <a-button type="primary" size="small" @click="addYjdd()" >添加押金</a-button>
                  </a-col>
              </a-row>
              <a-divider/>
              <div v-if="hydropowerFlag">
                <a-form-item
                  label="水電周期"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-select  style="width: 100%" placeholder="请选择水電周期" v-decorator="['hydropowercycle', { initialValue: 1 }]">
                        <a-select-option v-for="(item,index) in 18" :key="index" :value="item">{{ item }}月</a-select-option>
                    </a-select>
                  </a-form-item>
                <a-form-item
                  label="賬單起始日"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-select style="width: 100%" placeholder="请选择賬單起始日" v-decorator="['hydropowerBillStart', { initialValue: 0 }]">
                        <a-select-option :key="0" :value="0">起租日</a-select-option>
                        <!-- <a-select-option v-for="(item,index) in 31" :key="index" :value="item">{{ item }}号</a-select-option> -->
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    label="收租日"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-radio-group placeholder="请选择收租日" @change="onHydropowerBillEndTypeChange" v-decorator="['hydropowerBillEndType']">
                      <a-radio :style="radioStyle" :key="0" :value="0">提前</a-radio>
                      <div>
                        <a-form-item label="">
                          <a-input-number
                          :min="1"
                          :max="365"
                          :disabled="hydropowerBillEndTqDataable"
                          style="width:100%"
                          placeholder="请输入账单收租日提前几日"
                          v-decorator="['hydropowerBillEndTqData', { initialValue: 15 }]"/>
                          相较账单起始日提前几天
                        </a-form-item>
                      </div>
                      <a-radio :style="radioStyle" :key="1" :value="1">固定</a-radio>
                      <div  style="width: 100%">
                        <a-form-item  label="">
                          <a-select :disabled="hydropowerBillEndGdmonthDataDataable"  placeholder="请选择账单收租日固定几月" style="width: 100%" v-decorator="['hydropowerBillEndGdmonthData', { initialValue: 0 }]">
                            <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGdmonthDataData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                          </a-select>
                        </a-form-item>
                        <a-form-item >
                          <a-select :disabled="hydropowerBillEndGdmonthDataDataable"   placeholder="请选择账单收租日固定几日" style="width: 100%" v-decorator="['hydropowerBillEndGddayData', { initialValue: 5 }]">
                            <a-select-option  style="width: 100%"  v-for="(item,index) in billEndGddayDataData" :key="index" :value="item">{{ item }}號</a-select-option>
                          </a-select>
                        </a-form-item>
                      </div>
                    </a-radio-group>
                  </a-form-item>
                  <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item
                    label="水電物業"
                    :labelCol="labelCol_JG"
                    :wrapperCol="wrapperCol_JG">
                    <a-table
                                size="middle"
                                :columns="columnsFy"
                                :dataSource="fyData"
                                :pagination="false"
                                :loading="memberLoading"
                              >
                              <template slot="amount" slot-scope="text, record">
                                <a-input-number
                                    style="width:100%"
                                    :disabled="record.type === '3' || record.type === 3"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'amount')"
                                    :step="10"/>
                              </template>
                              <template slot="solder" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'solder')"
                                    :step="10"/>
                              </template>
                              <template slot="magnification" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'magnification')"
                                    :step="10"/>
                              </template>
                              <template slot="patchlossrate" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'patchlossrate')"
                                    :step="10"/>
                              </template>
                              <template slot="initialreading" slot-scope="text, record">
                                <a-input-number
                                    v-show="record.type === '2' || record.type === 2"
                                    style="width:100%"
                                    :precision="2"
                                    :min="0"
                                    :value="text"
                                    :max="99999999"
                                    @change="e => handleFyChange(e,record.key, 'initialreading')"
                                    :step="10"/>
                              </template>
                              <template slot="ydzd" slot-scope="text, record">
                                <span  v-if="record.type !== '2' && record.type !== 2">
                                  <a-checkbox :default-checked="record.ydzd === 1" :disabled="!hydropowerChangeflg" @change="e => handleFyChange(e,record.key,'ydzd')">
                                    移到租金賬單
                                  </a-checkbox>
                                </span>
                              </template>
                              <template slot="operation" slot-scope="text, record">
                                <a @click="removeFy(record.key)">删除</a>
                              </template>
                      </a-table>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row  type="flex" justify="space-around" align="middle">
                <a-col :span="4">
                  <a-button type="primary" size="small" @click="addFy()" >添加費用</a-button>
                </a-col>
              </a-row>
               </div>
      </a-form>
    </a-spin>
    <add-yj-form ref="addYjForm" @ok="yjhandleOk" />
    <add-expenses-form ref="addExpensesForm" @ok="fyhandleOk" />
  </a-modal>
</template>

<script>
  import addYjForm from '../busrealestate/addYjForm.vue'
  import addExpensesForm from '../busrealestate/addExpensesForm.vue'
  import { getDepositListByLeaseId } from '@/api/modular/main/roomdeposit/roomDepositManage'
  import { getExpensesListByLeaseId } from '@/api/modular/main/roomexpenses/roomExpensesManage'
  import { houseLeaseFyEdit } from '@/api/modular/main/houselease/houseLeaseManage'
  import moment from 'moment'
  export default {
     components: {
       addYjForm,
       addExpensesForm
    },
    data () {
      return {
        // 机构行样式
        labelCol_JG: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol_JG: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        hydropowerFlag: false,
        form: this.$form.createForm(this),
        memberLoading: false,
        radioStyle: {
          display: 'block',
          height: '30px',
          lineHeight: '30px'
        },
        billEndGdmonthDataData: [ { 'code': 12, 'name': '提前12月' }, { 'code': 11, 'name': '提前11月' }, { 'code': 10, 'name': '提前10月' }, { 'code': 9, 'name': '提前9月' }, { 'code': 8, 'name': '提前8月' }, { 'code': 7, 'name': '提前7月' }, { 'code': 6, 'name': '提前6月' }, { 'code': 5, 'name': '提前5月' }, { 'code': 4, 'name': '提前4月' }, { 'code': 3, 'name': '提前3月' }, { 'code': 2, 'name': '提前2月' }, { 'code': 1, 'name': '提前1月' }, { 'code': 0, 'name': '当月' }, { 'code': -1, 'name': '延後1月' }, { 'code': -2, 'name': '延後2月' }, { 'code': -3, 'name': '延後3月' }, { 'code': -4, 'name': '延後4月' }, { 'code': -5, 'name': '延後5月' }, { 'code': -6, 'name': '延後6月' }, { 'code': -7, 'name': '延後7月' }, { 'code': -8, 'name': '延後8月' }, { 'code': -9, 'name': '延後9月' }, { 'code': -10, 'name': '延後10月' }, { 'code': -11, 'name': '延後11月' }, { 'code': -12, 'name': '延後12月' } ],
        billEndGddayDataData: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ],
            // 水電物業租金水电分开收取標志
        hydropowerChangeflg: false,
        hydropowerBillEndTqDataable: false,
        hydropowerBillEndGdmonthDataDataable: false,
        columnsYj: [
          {
            title: '押金名稱',
            dataIndex: 'depositname',
            width: '30%',
            scopedSlots: { customRender: 'depositname' }
          },
          {
            title: '金額',
            dataIndex: 'amount',
            width: '30%',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '數量',
            dataIndex: 'quantity',
            width: '30%',
            scopedSlots: { customRender: 'quantity' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        columnsFy: [
          {
            title: '費用項',
            dataIndex: 'name',
            width: '15%',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '價格',
            dataIndex: 'amount',
            width: '10%',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '保底用量',
            dataIndex: 'solder',
            width: '15%',
            scopedSlots: { customRender: 'solder' }
          },
          {
            title: '倍率',
            dataIndex: 'magnification',
            width: '10%',
            scopedSlots: { customRender: 'magnification' }
          },
          {
            title: '表損率%',
            dataIndex: 'patchlossrate',
            width: '10%',
            scopedSlots: { customRender: 'patchlossrate' }
          },
          {
            title: '初始讀數',
            dataIndex: 'initialreading',
            width: '15%',
            scopedSlots: { customRender: 'initialreading' }
          },
          {
            title: '移到租金賬單',
            dataIndex: 'ydzd',
            width: '15%',
            scopedSlots: { customRender: 'ydzd' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        yjData: [],
        fyData: []
      }
    },
    methods: {
      moment,
      // 初始化方法
      edit (record) {
        this.visible = true
        const id = record.id
        this.getYjData(id)
        this.getFyData(id)
        this.hydropowerFlag = record.hydropower === 1
        this.hydropowerChangeflg = record.hydropower === 1
        this.onsDBillEndChange(record.hydropower)
        setTimeout(() => {
          this.form.setFieldsValue(
            {
              id: record.id,
              roomId: record.roomId,
              hydropowercycle: record.hydropowercycle,
              hydropowerBillEndType: record.hydropowerBillEndType,
              hydropowerBillEndTqData: record.hydropowerBillEndTqData,
              hydropowerBillEndGdmonthData: record.hydropowerBillEndGdmonthData,
              hydropowerBillEndGddayData: record.hydropowerBillEndGddayData
            }
          )
        }, 100)
      },
      getYjData(id) {
        this.yjData = []
        getDepositListByLeaseId(id).then((res) => {
          if (res.code === 200) {
            this.yjData = res.data
          } else {
            this.$message.error('查詢失敗')//  + res.message
          }
        })
      },
      getFyData(id) {
        this.fyData = []
        getExpensesListByLeaseId(id).then((res) => {
          if (res.code === 200) {
            this.fyData = res.data
          } else {
            this.$message.error('查詢失敗')//  + res.message
          }
        })
      },
      /**
       * 删除押金
       */
      removeYj (key) {
        const newData = this.yjData.filter(item => item.key !== key)
        this.yjData = newData
      },
      /**
       * 押金选择子表单单项触发
       */
      handleYjChange (value, key, column) {
        const newData = [...this.yjData]
        const target = newData.find(item => key === item.key)
        if (target) {
          target[column] = value
          this.yjData = newData
        }
      },
      // 添加押金
      addYjdd() {
        this.$refs.addYjForm.add(this.yjData)
      },
      yjhandleOk (param) {
        const selectedRowKeysYjlen = param.length
        if (selectedRowKeysYjlen > 0) {
           for (var i = 0; i < selectedRowKeysYjlen; i++) {
              var quantityNum = 0
              if (param[i].deposittype === '1') {
                quantityNum = 1
              }
              this.yjData.push({ key: param[i].key, disabled: true, depositname: param[i].depositname, depositid: param[i].depositid, deposittype: param[i].deposittype, amount: 0.00, quantity: quantityNum })
           }
        }
      },
      onsDBillEndChange (e) {
        if (e === 0) {
          this.hydropowerBillEndTqDataable = false
          this.hydropowerBillEndGdmonthDataDataable = true
        } else {
          this.hydropowerBillEndTqDataable = true
          this.hydropowerBillEndGdmonthDataDataable = false
        }
      },
      onHydropowerBillEndTypeChange (e) {
        if (e.target.value === 0) {
          this.hydropowerBillEndTqDataable = false
          this.hydropowerBillEndGdmonthDataDataable = true
        } else {
          this.hydropowerBillEndTqDataable = true
          this.hydropowerBillEndGdmonthDataDataable = false
        }
      },
      // 费用表
      addFy() {
        this.$refs.addExpensesForm.add(this.fyData)
      },
      handleFyChange (value, key, column) {
        if (column === 'ydzd') {
          var ydzd = 1
          if (!value.target.checked) {
            ydzd = 0
          }
          const newData = [...this.fyData]
          const target = newData.find(item => key === item.key)
          if (target) {
            target[column] = ydzd
            this.fyData = newData
          }
        } else {
          const newData = [...this.fyData]
          const target = newData.find(item => key === item.key)
          if (target) {
            target[column] = value
            this.fyData = newData
          }
        }
      },
      removeFy(key) {
        const newData = this.fyData.filter(item => item.key !== key)
        this.fyData = newData
      },
      // 费用确认回调
      fyhandleOk(param) {
        const selectedRowKeysYjlen = param.length
        if (selectedRowKeysYjlen > 0) {
           for (var i = 0; i < selectedRowKeysYjlen; i++) {
              this.fyData.push({ key: param[i].key, name: param[i].name, costid: param[i].costid, type: param[i].type, amount: 0.00, solder: 0, magnification: 1, patchlossrate: 0.00, initialreading: 0, ydzd: 1 })
           }
        }
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.yjData = this.yjData
            values.fyData = this.fyData
            houseLeaseFyEdit(values).then((res) => {
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', '')
                this.handleCancel()
              } else {
                this.$message.error(res.msg)//  + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.hydropowerFlag = false
        this.yjData = []
        this.fyData = []
      }
    }
  }
</script>
